package com.labot.dto.mapper;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.springframework.dao.DataIntegrityViolationException;

import com.labot.dto.UserDto;
import com.labot.model.Role;
import com.labot.model.User;


public class UserMapper {
	
	public static UserDto mapModelToDto(User source) {
		//Copiar las propiedades por Reflection
		UserDto target = new UserDto();
		try {
			BeanUtilsBean.getInstance().getConvertUtils().register(false, false, 0);
			BeanUtils.copyProperties(target, source);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		//Generar las listas de String
		Set<String> rolesTarget = new HashSet<String>();
		for (Role rol : source.getRoles()) {
			rolesTarget.add(rol.getAuthority());
		}
		target.setRoles(rolesTarget);
        return target;
    }
	
	public static List<UserDto> mapModelListToDtoList(List<User> source) {
		List<UserDto> target = new ArrayList<UserDto>();
		for (User user : source) {
			target.add(mapModelToDto(user));
		}
		return target;
	}
	
	public static User mapDtoToModel(UserDto source, User target, Set<Role> roles) throws DataIntegrityViolationException {
		//Verificar el id de Hibernate...
		boolean isNew = false;
		if (source.getId() == null) {
			isNew = true;
		}
		//Copiar las propiedades por Reflection
		try {
			BeanUtilsBean.getInstance().getConvertUtils().register(false, false, 0);
			BeanUtils.copyProperties(target, source);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		
		/**
		 * Si los roles no son NULL se los agrego al User
		 */
		if (roles != null) {			
			target.getRoles().clear(); // APF-788: Removing roles from user doesn't work
			for (Role role : roles) {
				target.addRole(role);
			}
		}
		if (isNew) {
			target.setId(null);
		}
		
        return target;
    }
	
}
